<template>
  <div class="contentView" v-loading="formLoading" :style="`height:${contentHeight}px`">
    <div class="routeHeader mb-5px">
      <el-button
        @click="submitForm"
        type="primary"
        :disabled="formLoading"
        v-hasPermi="['config:wage-process-valuation:save']"
        >保 存</el-button
      >
      <el-button @click="close">关 闭</el-button>
    </div>
    <el-scrollbar :style="`height:${contentHeight - 63}px`">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        v-loading="formLoading"
      >
        <el-form-item label="工序名称" prop="dictProcessName">
          <el-select
            v-model="formData.dictProcessName"
            placeholder="请选择工序名称"
            @change="handleSelectChange"
            clearable
            class="!w-220px"
            :disabled="formType.includes('update')"
          >
            <el-option
              v-for="(dict, index) in getIntDictOptions(DICT_TYPE.CRAFT_PROCESS_NAME)"
              :key="index"
              :label="dict.label"
              :value="dict.value"
              :disabled="dict.label == '焊接' || dict.label == '组装' || dict.label == '试机'"
            />
          </el-select>
        </el-form-item>
        <!-- 下料 -->
        <div v-if="isShowBaiting">
          <el-form-item label="单价" prop="unitPrice">
            <el-input-number
              :min="0"
              class="!w-220px"
              v-model="formData.unitPrice"
              placeholder="请输入单价"
              controls-position="right"
            />
          </el-form-item>
          <el-form-item label="单位" prop="dictValuationUnit">
            <el-select
              v-model="formData.dictValuationUnit"
              placeholder="重量"
              :disabled="isShowBaiting"
              class="!w-220px"
            >
              <el-option
                v-for="(dict, index) in getIntDictOptions(DICT_TYPE.CONFIG_WAGE_VALUATION_UNIT)"
                :key="index"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="工艺类型" prop="dictCraftType">
            <el-select
              class="!w-220px"
              v-model="formData.dictCraftType"
              placeholder="请选择工艺类型"
            >
              <el-option
                v-for="(dict, index) in getIntDictOptions(DICT_TYPE.CONFIG_WAGE_CRAFT_TYPE)"
                :key="index"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="下料类型" prop="dictBaitingType">
            <el-select
              class="!w-220px"
              v-model="formData.dictBaitingType"
              placeholder="请选择下料类型"
            >
              <el-option
                v-for="(dict, index) in getIntDictOptions(DICT_TYPE.CONFIG_WAGE_BAITING_TYPE)"
                :key="index"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="dictProcessValuationStatus">
            <el-select
              v-model="formData.dictProcessValuationStatus"
              placeholder="请选择状态"
              clearable
              class="!w-220px"
            >
              <el-option
                v-for="(dict, index) in getIntDictOptions(
                  DICT_TYPE.CONFIG_WAGE_PROCESS_VALUATION_STATUS
                )"
                :key="index"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </div>
        <!-- 机加 -->
        <div v-if="isShowMachining">
          <el-form-item label="单价" prop="unitPrice">
            <el-input
              :disabled="isShowMachining"
              class="!w-220px"
              v-model="formData.unitPrice"
              placeholder="请输入单价"
            />
          </el-form-item>
          <el-form-item label="单位" prop="dictValuationUnit">
            <el-select
              v-model="formData.dictValuationUnit"
              placeholder="个（整装）"
              :disabled="isShowMachining"
              class="!w-220px"
            >
              <el-option
                v-for="(dict, index) in getIntDictOptions(DICT_TYPE.CONFIG_WAGE_VALUATION_UNIT)"
                :key="index"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="图纸图号" prop="drawingNumber">
            <el-input
              class="!w-220px"
              v-model="formData.drawingNumber"
              placeholder="请输入图纸图号"
            />
          </el-form-item>
          <el-form-item label="机加工序" prop="dictMachiningProcess">
            <el-select
              class="!w-220px"
              v-model="formData.dictMachiningProcess"
              placeholder="请选择机加"
            >
              <el-option
                v-for="(dict, index) in getIntDictOptions(DICT_TYPE.MACHINING_PROCESS)"
                :key="index"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="dictProcessValuationStatus">
            <el-select
              v-model="formData.dictProcessValuationStatus"
              placeholder="请选择状态"
              clearable
              class="!w-220px"
            >
              <el-option
                v-for="(dict, index) in getIntDictOptions(
                  DICT_TYPE.CONFIG_WAGE_PROCESS_VALUATION_STATUS
                )"
                :key="index"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="项目单价">
            <el-button @click="selectUnivalent" type="primary">选择项目单价</el-button>
          </el-form-item>
        </div>
        <!-- 油漆 布线 电柜 -->
        <div v-if="isShowPaint">
          <el-form-item label="单价" prop="unitPrice">
            <el-input
              :disabled="isShowPaint"
              class="!w-220px"
              v-model="formData.unitPrice"
              placeholder="请输入单价"
            />
          </el-form-item>
          <el-form-item label="单位" prop="dictValuationUnit">
            <el-select
              v-model="formData.dictValuationUnit"
              placeholder="个（记件）"
              :disabled="isShowPaint"
              class="!w-220px"
            >
              <el-option
                v-for="(dict, index) in getIntDictOptions(DICT_TYPE.CONFIG_WAGE_VALUATION_UNIT)"
                :key="index"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="图纸图号" prop="drawingNumber">
            <el-input
              class="!w-220px"
              v-model="formData.drawingNumber"
              placeholder="请输入图纸图号"
            />
          </el-form-item>
          <el-form-item label="状态" prop="dictProcessValuationStatus">
            <el-select
              v-model="formData.dictProcessValuationStatus"
              placeholder="请选择状态"
              clearable
              class="!w-220px"
            >
              <el-option
                v-for="(dict, index) in getIntDictOptions(
                  DICT_TYPE.CONFIG_WAGE_PROCESS_VALUATION_STATUS
                )"
                :key="index"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="项目单价">
            <el-button @click="selectPaintUnivalent" type="primary">选择项目单价</el-button>
          </el-form-item>
        </div>
      </el-form>
      <!-- 机加 -->
      <div class="pb-20px" v-if="isShowMachining">
        <el-table v-loading="loading" :data="machiningData" border>
          <el-table-column label="序号" align="center" type="index" width="80" />
          <el-table-column label="零件名称" align="center" prop="partsName" />
          <el-table-column label="规格" align="center" prop="specification" />
          <el-table-column label="加工工序" align="center" prop="processing" />
          <el-table-column label="单位" align="center" prop="unit" />
          <el-table-column label="单价 (元)" align="center" prop="unitPrice" />
          <el-table-column label="数量" align="center" width="180" prop="quantity">
            <template #default="scope">
              <el-input-number
                v-nextInput="'quantity'"
                name="quantity"
                :min="0"
                v-model="scope.row.quantity"
                controls-position="right"
              />
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" prop="remark" />
          <el-table-column label="操作" align="center" width="80">
            <template #default="scope">
              <el-button link type="danger" @click="machiningDelete(scope.$index)"
                >移除行</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 油漆 布线 电柜 -->
      <div class="pb-20px" v-if="isShowPaint">
        <el-table v-loading="loading" :data="paintData" border>
          <el-table-column label="序号" align="center" type="index" width="80" />
          <el-table-column label="设备名称" align="center" prop="deviceName" />
          <el-table-column label="产品规格" align="center" prop="productStandard" />
          <el-table-column label="项目内容" align="center" prop="projectContent" />
          <el-table-column label="工时" align="center" prop="manHour" />
          <!-- <el-table-column label="单位" align="center" prop="unit" /> -->
          <el-table-column label="单价 (元)" align="center" prop="unitPrice" />
          <el-table-column label="数量" align="center" prop="quantity" width="180">
            <template #default="scope">
              <el-input-number
                v-nextInput="'quantity'"
                name="quantity"
                :min="0"
                v-model="scope.row.quantity"
                controls-position="right"
              />
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" prop="remark" />
          <el-table-column label="操作" align="center" width="80">
            <template #default="scope">
              <el-button link type="danger" @click="paintDelete(scope.$index)">移除行</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-scrollbar>
  </div>
  <!-- 表单弹窗：机加 -->
  <MachiningPaintForm ref="dialogFormRef" @success="selectData" />
  <!-- 表单弹窗：油漆 -->
  <PaintElectricianForm ref="paintFormRef" @success="selectPaintData" />
</template>
<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import * as WageProcessValuationApi from '@/api/config/wageProcessValuation'
import { useTagsViewStore } from '@/store/modules/tagsView'
import MachiningPaintForm from './MachiningPaintForm.vue'
import PaintElectricianForm from './PaintElectricianForm.vue'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const { query } = useRoute() // 路由的查询

const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const loading = ref(false) // 机价表单
const machiningData = ref([]) // 机加数据
const paintData = ref([]) // 油漆 布线 电柜数据
const isShowBaiting = ref(false) // 下料
const isShowMachining = ref(false) // 机加
const isShowPaint = ref(false) // 油漆 布线  电柜
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  dictProcessName: undefined,
  drawingNumber: undefined,
  dictBaitingType: undefined,
  dictProcessValuationStatus: undefined,
  remark: undefined,
  dictCraftType: undefined,
  unitPrice: undefined,
  dictValuationUnit: undefined,
  dictMachiningProcess: undefined
})
const formRules = reactive({
  dictProcessName: [{ required: true, message: '工序名称不能为空', trigger: 'blur' }],
  dictProcessValuationStatus: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
  // unitPrice: [{ required: true, message: '单价不能为空', trigger: 'blur' }],
  dictCraftType: [{ required: true, message: '工艺类型不能为空', trigger: 'blur' }],
  dictBaitingType: [{ required: true, message: '下料类型不能为空', trigger: 'blur' }],
  drawingNumber: [{ required: true, message: '图纸图号不能为空', trigger: 'blur' }],
  dictMachiningProcess: [{ required: true, message: '机加工序不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async () => {
  const type = query.type as any
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (query.id != 'undefined') {
    let id = query.id as any
    formLoading.value = true
    try {
      const data = await WageProcessValuationApi.getWageProcessValuation(id)
      handleSelectChange(data.dictProcessName)
      formData.value = data
      machiningData.value = data.machiningList
      paintData.value = data.paintList
    } finally {
      formLoading.value = false
    }
  }
}

/** 选择显示 */
const changeName = ref()
const paintName = ref()
const handleSelectChange = (val) => {
  changeName.value = val
  const data = getIntDictOptions(DICT_TYPE.CRAFT_PROCESS_NAME)
  const processName = data.find((item) => item.value == val)
  if (processName?.label == '下料') {
    isShowBaiting.value = true
    isShowMachining.value = false
    isShowPaint.value = false
    changeForm()
  } else if (processName?.label == '机加') {
    isShowMachining.value = true
    isShowBaiting.value = false
    isShowPaint.value = false
    changeForm()
  } else if (
    processName?.label == '油漆' ||
    processName?.label == '布线' ||
    processName?.label == '电柜'
  ) {
    paintName.value = processName.label
    isShowPaint.value = true
    isShowBaiting.value = false
    isShowMachining.value = false
    changeForm()
  }
}

/** 提交表单 */
const submitForm = async () => {
  const checkTable = await check()
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  if (!checkTable) return

  // 提交请求
  formLoading.value = true
  try {
    let data = {
      ...formData.value,
      relationVo: []
    } as unknown as WageProcessValuationApi.WageProcessValuationVO
    if (isShowMachining.value) {
      data.relationVo = machiningData.value as any
    } else if (isShowPaint.value) {
      data.relationVo = paintData.value as any
    }
    if (formType.value === 'create') {
      await WageProcessValuationApi.createWageProcessValuation(data)
      message.success(t('common.createSuccess'))
      goBack()
    } else {
      await WageProcessValuationApi.updateWageProcessValuation(data)
      message.success(t('common.updateSuccess'))
      goBack()
    }
  } finally {
    formLoading.value = false
  }
}

/** 机加选中的单价 */
const selectData = (data) => {
  machiningData.value = data
}

/** 油漆选中的单价 */
const selectPaintData = (data) => {
  paintData.value = data
}

//必填校验
const check = async () => {
  if (isShowMachining.value) {
    let data = machiningData.value as any
    if (data.length === 0) {
      message.warning(t('请选择项目单价'))
      return false
    }
    for (let i = 0; i < data.length; i++) {
      if (!data[i].quantity) {
        message.warning(t('数量不能为空'))
        return false
      }
    }
  } else if (isShowPaint.value) {
    let data = paintData.value as any
    if (data.length === 0) {
      message.warning(t('请选择项目单价'))
      return false
    }
    for (let i = 0; i < data.length; i++) {
      if (!data[i].quantity) {
        message.warning(t('数量不能为空'))
        return false
      }
    }
  }
  return true
}

/** 机加删除行 */
const machiningDelete = (index) => {
  machiningData.value.splice(index, 1)
}

/** 选择机加项目单价 */
const dialogFormRef = ref()
const selectUnivalent = () => {
  const ids = machiningData.value.map((item) => {
    return (item as any).id
  })
  dialogFormRef.value.open(ids)
}

/** 油漆,电柜,布线删除行 */
const paintDelete = (index) => {
  paintData.value.splice(index, 1)
}

/** 油漆,电柜,布线项目单价 */
const paintFormRef = ref()
const selectPaintUnivalent = () => {
  const ids = paintData.value.map((item) => {
    return (item as any).id
  })
  paintFormRef.value.open(ids)
}

/** 切换重置表单 */
const changeForm = () => {
  formData.value = {
    id: undefined,
    dictProcessName: changeName.value,
    drawingNumber: undefined,
    dictBaitingType: undefined,
    dictProcessValuationStatus: undefined,
    remark: undefined,
    dictCraftType: undefined,
    unitPrice: undefined,
    dictValuationUnit: undefined,
    dictMachiningProcess: undefined
  }
  machiningData.value = []
  formRef.value?.resetFields()
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    dictProcessName: undefined,
    drawingNumber: undefined,
    dictBaitingType: undefined,
    dictProcessValuationStatus: undefined,
    remark: undefined,
    dictCraftType: undefined,
    unitPrice: undefined,
    dictValuationUnit: undefined,
    dictMachiningProcess: undefined
  }
  formRef.value?.resetFields()
}

// 关闭
const close = async () => {
  ElMessageBox.confirm('是否保存填写内容?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      submitForm()
    })
    .catch(() => {
      goBack()
    })
}

// 返回
const tagsViewStore = useTagsViewStore()
const route = useRouter() // 路由
const goBack = () => {
  //获取当前路由并删除tagView
  tagsViewStore.delView(route.currentRoute.value)
  route.push({
    path: '/config/config/salaryAssessment/wageProcessValuation'
  })
}

const contentHeight = ref(0)
onMounted(async () => {
  contentHeight.value = document.body.clientHeight - 127
  await open()
})
</script>
